const path = require('path');
const fs = require('fs');

// 遍历目录及子目录获取文件路径，半尾递归
function getDirectories(dir, isDirectory, arr) {
  if(isDirectory) {
    const dirents = fs.readdirSync(dir, { withFileTypes: true });
    dirents.forEach(dirent => {
      // 拼接上级目录路径和子目录名称
      const subPath = path.join(dir, dirent.name);
      // 递归遍历子目录
      getDirectories(subPath, dirent.isDirectory(), arr)
    });
  } else {
    arr.push(dir);
  }
}

(async function coverFiles() {
  const sourcePath = path.join(__dirname, './node_modules');
  const sources = [];
  getDirectories(sourcePath, true, sources);

  try {
    // 覆盖所有对应路径的文件
    sources.forEach(src => {
      const dest = path.join(__dirname, '../', src.replace(__dirname, ''));
      const backup = src + ".bak";
      // TODO 此处用异步方法性能更好
      fs.copyFileSync(dest, backup);
      fs.copyFileSync(src, dest);
    });

    console.log("The project has been enhanced successfully! ");

  } catch (error) {
    console.log("Project enhances failed! ");
    console.log(error);
  }
})();
